<template>
  <div class='container'>
    <div style="margin-bottom: 12px;">
      <el-button style="margin-right: 10px;" @click="handleCreate" type="success" icon="el-icon-plus">新增</el-button>
      <el-button style="margin-right: 10px;" @click="handleDelete" type="danger" icon="el-icon-delete">删除</el-button>
    </div>
    <el-table stripe row-key="id"
      :data="tableData" v-loading="listLoading" element-loading-text="加载中..." border fit
      highlight-current-row @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="55">
      </el-table-column>
      <!--<el-table-column align="center" type="index" label="序号" width="55">-->
      <!--</el-table-column>-->
      <el-table-column align="center" label="图片预览" width="480">
        <template slot-scope="scope">
          <img style="max-height: 270px!important;" :src="scope.row.pictureUrl" :alt="scope.row.pictureName">
        </template>
      </el-table-column>
      <el-table-column align="center" label="栏目">
        <template slot-scope="scope">
          <span>{{scope.row.relationName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center" label="操作" width="90" class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button class="button-icon el-icon-edit" type="primary" size="mini"
              @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageNum"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog :close-on-click-modal="false" @close="pictureList = []" :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible" width="805px">
      <el-form
        :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="130px"
        style='margin: 24px;'
      >
        <el-form-item v-if="dialogStatus==='create'" label="新增图片" prop="pictureList">
          <el-upload
            :action="imageUploadUrl"
            :headers="{Authorization: 'Bearer ' + $store.getters.token}"
            list-type="picture-card"
            :multiple="true"
            :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handlePictureCardRemove"
            :on-success="handlePictureCardCallback"
            :file-list="pictureList">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item v-if="dialogStatus==='update'" label="新增图片" prop="pictureList">
          <el-upload
            :action="imageUploadUrl"
            :headers="{Authorization: 'Bearer ' + $store.getters.token}"
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handlePictureReplace"
            :file-list="pictureList">
            <img v-if="temp.pictureList[0]" :src="temp.pictureList[0].url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="所属栏目" prop="classChoose">
          <el-popover
            placement="bottom-start"
            trigger="click"
            @show="filterText5 = ''"
            v-model="visiblePopover"
          >
            <el-select
              :clearable="true"
              popper-class="hide" slot="reference" v-model="temp.classChoose" type="text"
              placeholder="请输入"
            >
              <el-option
                v-for="(item, index) in options" v-show="false" :key="index" :value="item.id" :label="item.name"
              ></el-option>
            </el-select>
            <el-input
              placeholder="输入关键字进行过滤"
              v-model="filterText5">
            </el-input>
            <el-tree
              :filter-node-method="filterNode"
              ref="tree5" :props="props" :data="treeList" :highlight-current="false" node-key="code"
              :default-expanded-keys="[0]" :render-content="renderClassContent"
            >
            </el-tree>
          </el-popover>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    classImageList,
    classImageDelete,
    classImageAdd,
    classImageUpdate,
    imageUploadUrl
  } from '../../api/imageManagement'
  import { classList } from '../../api/article'
  import pinyin from 'pinyin'

  export default {
    name: 'List',
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      },
      filterText5(val) {
        this.$refs.tree5.filter(val)
      },
      pictureList() {
        this.temp.pictureList = this.pictureList.map(e => {
          if (e.response) {
            return e.response.Data[0]
          } else {
            return e
          }
        })
      }
    },
    created() {
      this.getList()
      this.getClass()
    },
    methods: {
      filterNode(value, data) {
        // console.log(value, data)
        if (!value) return true
        return data.name.indexOf(value) !== -1 || pinyin(data.name, {
          style: pinyin.STYLE_FIRST_LETTER,
          heteronym: true
        }).join('').indexOf(value) !== -1
      },
      handleSelectionChange(val) {
        this.multipleSelection = val.map(e => e.id)
      },
      getList() {
        this.listLoading = false
        classImageList(this.listQuery).then(response => {
          this.tableData = response.Data
          this.total = response.PageInfo.Total * 1
          this.listLoading = false
        })
      },
      getClass() {
        const params = {
          pageNum: 1,
          pageSize: 99999
        }
        classList(params).then(response => {
          const temp = {}
          const result = []
          const data = response.Data
          const length = data.length
          for (let i = 0; i < length; i++) {
            temp[data[i].id] = data[i]
            this['options'].push(data[i])
          }
          for (let i = 0; i < length; i++) {
            if (temp[data[i].id].parentId && temp[data[i].parentId]) {
              if (!temp[data[i].parentId].children) {
                temp[data[i].parentId].children = []
              }
              temp[data[i].parentId].children.push(temp[data[i].id])
            } else {
              result.push(temp[data[i].id])
            }
          }
          this['treeList'][0].children = result
        })
      },
      renderClassContent(h, { node, data, store }) {
        return (
          <span class={(node.isLeaf && node.level > 1) ? 'custom-tree-node' : 'custom-tree-node custom-tree-notLeaf'}>
            <span>{node.label}</span>
            <span>
              {(node.level > 1 && node.isLeaf) ? <el-button
                size='mini' type='text'
                on-click={() => {
                  this.temp.classChoose = data.id
                  this.visiblePopover = false
                }}
              >选择</el-button> : ''}
            </span>
          </span>
        )
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: '',
          pictureList: [],
          classChoose: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handlePictureCardRemove(file, fileList) {
        this.pictureList = fileList
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handlePictureCardCallback(response, file, fileList) {
        this.pictureList = fileList
      },
      handlePictureReplace(response, file) {
        this.pictureList = [file]
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const params = {
              pictureIds: this.temp.pictureList.map(e => e.id),
              relationId: this.temp.classChoose
            }
            classImageAdd(params).then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.pictureList = [{
          name: row.pictureName,
          url: row.pictureUrl,
          id: row.pictureId
        }]
        this.temp.classChoose = row.relationId
        this.temp.id = row.id
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const param = {
              pictureId: this.temp.pictureList[0].id,
              relationId: this.temp.classChoose,
              id: this.temp.id
            }
            classImageUpdate(param).then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete() {
        if (this.multipleSelection.length === 0) return
        this.$confirm('确认删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          classImageDelete({ batchIds: this.multipleSelection }).then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      beforeUpload(file) {
        const isJPG = [
          'image/jpeg',
          'image/svg+xml',
          'image/bmp',
          'image/webp',
          'image/vnd.dwg',
          'image/vnd.dxf',
          'image/gif',
          'image/jp2',
          'image/tiff',
          'image/vnd.svf',
          'image/png'
        ].indexOf(file.type) > -1
        const isLt2M = file.size / 1024 / 1024 < 1
        if (!isJPG) {
          this.$message.error('请上传图片文件！')
        }
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 1MB!')
        }
        return isJPG && isLt2M
      }
    },
    data() {
      return {
        imageUploadUrl: imageUploadUrl,
        dialogVisible: false,
        dialogImageUrl: '',
        filterText5: '',
        treeList: [{ name: '栏目列表', code: 0, children: [] }],
        options: [],
        props: {
          label: 'name',
          id: 'code',
          key: 'code'
        },
        multipleSelection:[],
        visiblePopover: false,
        pictureList: [],
        allWordList: [],
        total: null,
        listLoading: false,
        showButton: false,
        tableName: '词汇标签管理',
        time: ['', ''],
        listQuery: {
          pageNum: 1,
          pageSize: 20,
          search: undefined
        },
        filterText: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogStatus: '',
        dialogFormVisible: false,
        tableData: [],
        temp: {
          id: '',
          pictureList: [],
          classChoose: ''
        },
        rules: {
          pictureList: [{ required: true, message: '请输入...', trigger: 'change' }],
          classChoose: [{ required: true, message: '请输入...', trigger: 'change' }]
        }
      }
    }
  }
</script>

<style type="scss" scoped>
  .col {
    margin: auto;
  }

  .card-body {
    margin-top: 1rem;
  }

  .form {
    max-width: 500px !important;
    margin: auto !important;
  }
</style>

<style>
  .hide {
    display: none;
  }

  .el-tag {
    margin-right: 3px;
    background-color: rgba(64, 158, 255, .1);
    color: #409EFF;
    border-radius: 4px;
    padding: 0 3px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid rgba(64, 158, 255, .2);
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>


